package com.think.excel;

import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;

import java.io.InputStream;
import java.util.Collections;
import java.util.Map;

public class ExcelConfigDataLoader implements ConfigDataLoader<ExcelConfigDataResource> {

    @Override
    public ConfigData load(ConfigDataLoaderContext context, ExcelConfigDataResource resource)
            throws ConfigDataResourceNotFoundException {

        // 1. 添加资源存在性检查
        if (!resource.exists()) {
            throw new ConfigDataResourceNotFoundException(resource);
        }

        try (InputStream is = resource.getInputStream()) {
            // 2. 解析Excel内容
            Map<String, Object> configMap = ExcelReader.parseToMap(is);

            // 3. 构建带来源标识的PropertySource
            String sourceName = String.format("ExcelConfig[%s]", resource.getLocation());
            return new ConfigData(Collections.singletonList(
                    new ExcelPropertySource(sourceName, configMap)
            ));

        } catch (Exception e) {
            // 4. 异常处理规范化
            throw new ConfigDataResourceNotFoundException(resource, e);
        }
    }
}